﻿package org.kolonitsky.alexey.flashui
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class ToggleButton extends MovieClip
    {
        public static const STATE_UP:String = "up";
        public static const STATE_UP_SELECTED:String = "sup";
        public static const STATE_OVER:String = "over";
        public static const STATE_OVER_SELECTED:String = "sover";
        public static const STATE_DOWN:String = "down";
        public static const STATE_DOWN_SELECTED:String = "sdown";

        private var _selected: Boolean = false;

        /**
         * @property selected
         */
        public function get selected (): Boolean
        {
            return _selected
        }

        public function set selected (value:Boolean): void {
            _selected = value
        }

        /** Constructor **/
        public function ToggleButton()
        {
            super();
            stop();
            addEventListener(Event.ADDED_TO_STAGE, init)
        }

        public function updateState(state:String):void
        {
            if (existsLabel(state))
                gotoAndStop(state);
        }

        private var _reactArea: MovieClip;

        private function init (event:Event): void
        {
            _reactArea = MovieClip(getChildByName("reactArea"));
            if (_reactArea == null)
                _reactArea = this;
            _reactArea.useHandCursor = true;
            _reactArea.buttonMode = true;
            _reactArea.addEventListener(MouseEvent.ROLL_OUT, onRollOut);
            _reactArea.addEventListener(MouseEvent.ROLL_OVER, onRollOver);
            _reactArea.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
            _reactArea.addEventListener(MouseEvent.MOUSE_UP, onMouseDown);
        }

        private function onRollOut (event:MouseEvent): void
        {
            var l: String = _selected ? STATE_UP_SELECTED : STATE_UP;
            updateState(l);
        }

        private function onRollOver (event:MouseEvent): void
        {
            var l: String = _selected ? STATE_OVER_SELECTED : STATE_OVER;
            updateState(l);
        }
      
      
        private function onMouseDown (event:MouseEvent): void
        {
            var l: String = _selected ? STATE_DOWN_SELECTED : STATE_DOWN;
            updateState(l);
        }
      
      
        private function onMouseUp (event:MouseEvent): void
        {
            var l: String = _selected ? STATE_OVER_SELECTED : STATE_OVER;
            updateState(l);
            selected = !selected;
        }
      
      
        private function existsLabel (label:String): Boolean
        {
            for (var i:int=0; i < currentLabels.length; i++)
                if (currentLabels[i].name == label)
                    return true;
            return false
        }
   }
}